/*
 * Copyright (c) 2011, Nikolaus Moll
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 * * Neither the name of the gradecalculator.net nor the
 *   names of its contributors may be used to endorse or promote products
 *   derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 */
package net.gradecalculator.gui.qt.calculator.widgets;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import net.gradecalculator.core.GCCore;
import net.gradecalculator.core.interfaces.ICourseOfStudiesIdentifier;
import net.gradecalculator.core.interfaces.IElectiveModulesArea;
import net.gradecalculator.core.interfaces.IModuleList;
import net.gradecalculator.core.interfaces.IModuleListItem;
import net.gradecalculator.core.interfaces.IRegulationsItem;
import net.gradecalculator.core.interfaces.IStudent;
import net.gradecalculator.core.interfaces.IStudyRegulations;
import net.gradecalculator.gui.qt.calculator.interfaces.IRegulationsItemSelectionListener;
import net.miblounge.miglayout.qt.MigLayout;

import com.trolltech.qt.gui.QGroupBox;
import com.trolltech.qt.gui.QWidget;

public class SelectionsWidget extends QGroupBox implements IRegulationsItemSelectionListener
{
    private ICourseOfStudiesIdentifier identifier = null;
    private final MigLayout layout;
    private final Map<IRegulationsItem, ModuleListsSelectorWidget> groups;
    private final Map<IRegulationsItem, List<IElectiveModulesArea>> dependencies;

    private final IStudent student;

    public SelectionsWidget(final String title, final QWidget parent, final IStudent student)
    {
        super(title, parent);
        this.student = student;

        groups = new HashMap<IRegulationsItem, ModuleListsSelectorWidget>();
        dependencies = new HashMap<IRegulationsItem, List<IElectiveModulesArea>>();

        layout = new MigLayout("", "[shrink 0, 150::][grow]", "");
        setLayout(layout);

        setVisible(false);
    }

    private void clearLayout()
    {
        dependencies.clear();

        for (final ModuleListsSelectorWidget widget : groups.values()) {
            widget.remove();
        }

        groups.clear();
    }

    private IModuleList getSMLParent(final IRegulationsItem lists)
    {
        IRegulationsItem item = lists.getParent();
        while (item != null) {
            if (item instanceof IModuleList) {
                if (item.getParent() == null) {
                    // root list
                    return null;
                }
                return (IModuleList) item;
            }
            item = item.getParent();
        }

        return null;
    }

    private void addSLMDependency(final IRegulationsItem parent, final IElectiveModulesArea child)
    {
        final List<IElectiveModulesArea> list;
        if (dependencies.containsKey(parent)) {
            list = dependencies.get(parent);
        }
        else {
            list = new LinkedList<IElectiveModulesArea>();
            dependencies.put(parent, list);
        }

        list.add(child);
    }

    private boolean createGroups(final List<IElectiveModulesArea> list)
    {
        clearLayout();
        if (list.size() == 0) {
            return false;
        }

        for (final IElectiveModulesArea sml : list) {
            final ModuleListsSelectorWidget grp = new ModuleListsSelectorWidget(this, sml);
            grp.addSelectionListener(this);
            // TODO
            groups.put(sml, grp);

            final IModuleList parent = getSMLParent(sml);
            if (parent != null) {
                grp.setSelectionEnabled(false);
                addSLMDependency(parent, sml);
            }
        }

        for (final IModuleList modulesArea : student.getElectiveModulesAreas()) {
            final IRegulationsItem parent = modulesArea.getParent();

            if (!groups.containsKey(parent)) {
                continue;
            }
            final ModuleListsSelectorWidget grp = groups.get(parent);
            grp.setItemSelected(modulesArea.getName(), true);
        }

        return true;
    }

    public void apply()
    {
        final List<IModuleList> list = new LinkedList<IModuleList>();

        for (final IRegulationsItem parent : groups.keySet()) {
            final ModuleListsSelectorWidget grp = groups.get(parent);

            for (final String name : grp.getSelectedItems()) {
                list.add((IModuleList) parent.getChildByName(name));
            }
        }

        student.setElectiveModulesAreas(list);
    }

    public void setCourseOfStudiesDescription(final ICourseOfStudiesIdentifier identifier)
    {
        if (identifier == null) {
            if (this.identifier == null) {
                return;
            }

            this.identifier = null;
            clearLayout();
            setVisible(false);

            adjustParentSize();
            return;
        }

        if (identifier.equals(this.identifier)) {
            return;
        }

        this.identifier = identifier;
        final IStudyRegulations spodescription = GCCore.readRegulations(identifier);
        final List<IElectiveModulesArea> list = getSelectableModuleLists(spodescription.getModuleList());
        setVisible(createGroups(list));

        adjustParentSize();
    }

    private void adjustParentSize()
    {
        QWidget parent = parentWidget();
        while (parent != null) {
            parent.adjustSize();

            if (parent.isWindow()) {
                return;
            }

            parent = parent.parentWidget();
        }
    }

    private static List<IElectiveModulesArea> getSelectableModuleLists(final IModuleList root)
    {
        final List<IElectiveModulesArea> result = new ArrayList<IElectiveModulesArea>();
        for (final IModuleListItem m : root.getModules()) {
            if (!(m instanceof IElectiveModulesArea)) {
                continue;
            }
            final IElectiveModulesArea slm = (IElectiveModulesArea) m;

            result.add(slm);
            for (final IModuleList ml : slm.getModuleLists()) {
                result.addAll(getSelectableModuleLists(ml));
            }
        }

        return result;
    }

    @Override
    public void selectionChanged(final IRegulationsItem item, final boolean selected)
    {
        if (!dependencies.containsKey(item)) {
            return;
        }

        final List<IElectiveModulesArea> dependingLists = dependencies.get(item);
        for (final IElectiveModulesArea sml : dependingLists) {
            final ModuleListsSelectorWidget group = groups.get(sml);

            group.setSelectionEnabled(selected);
            selectionChanged(sml, selected);
        }
        adjustParentSize();
    }
}
